package com.rgs.pay.wechat.util;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * @author Ren Gaoshuai
 * @ClassName WechatSignUtils
 * @date 2022-08-17 21:30
 * 微信支付签名辅助类
 **/
public class WechatSignUtils {
    /**
     * 微信支付签名算法MD5
     * @param characterEncoding 编码格式  UTF-8
     * @param parameters 参数
     * @param wxKey 微信key
     * @return  签名
     */
    @SuppressWarnings("rawtypes")
    public static String createSign(String characterEncoding, SortedMap<Object,Object> parameters, String wxKey){

        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key="+wxKey);
//        System.out.println("字符串拼接后是："+sb);
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }

    /**
     * 是否签名正确,验证签名
     * @return boolean
     * @param  packageParams  签名参数
     *  @param  characterEncoding 字符 UTF-8
     *   @param  packageParams   签名参数
     */
    public static boolean isWxPaySign(String characterEncoding, SortedMap<Object, Object> packageParams) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if(!"sign".equals(k) && null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
            }
        }

//        sb.append("key=" + LoadProperties.getPayProperty("wx_key"));

        //算出摘要
        String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
        String wxPaySign = ((String)packageParams.get("sign")).toLowerCase();
        return wxPaySign.equals(mysign);
    }

}
